package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.service.ArticleHomeService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.article.service.ArticleFreemarkerService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private ArticleHomeService service;
    @Override
    @Async
    public void buildArticleToMinIO(ApArticle apArticle, String content) {
        //获取文章内容
        if (StringUtils.isNotBlank(content)){
            //通过freeMark生成html文章内容
            StringWriter sw=new StringWriter();
            Template template = null;
            try {
                template = configuration.getTemplate("article.ftl");
                //数据模型
                Map<String,Object> map=new HashMap<>();
                map.put("content", JSONArray.parseArray(content));
                //合成html数据
                template.process(map,sw);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //将这个文件上传到minIO
            InputStream inputStream = new ByteArrayInputStream(sw.toString().getBytes());
            String filePath = fileStorageService.uploadHtmlFile("", apArticle.getId() + ".html", inputStream);

            //更新文章表
            LambdaUpdateWrapper<ApArticle> wrapper=new LambdaUpdateWrapper<>();
            wrapper.eq(ApArticle::getId,apArticle.getId()).set(ApArticle::getStaticUrl,filePath);
            service.update(wrapper);
        }

    }
}
